import axios from 'axios'
import settings from '../utils/setting'
import router from '../router'
let requestData
let loadingE

const service = axios.create({
  timeout: 10000 // 超时时间
})

// 请求拦截
service.interceptors.request.use(
  (request) => {
    // token配置
    request.headers['token'] = sessionStorage.getItem("token") || ""
    /* 下载文件*/
    if (request.isDownLoadFile) {
      request.responseType = 'blob'
    }
    if (request.isUploadFile) {
      request.headers['Content-Type'] = 'multipart/form-data'
    }
    if(request.progress){
      request.onUploadProgress = request.progress
    } 
    requestData = request
    if (request.bfLoading) {
      loadingE = ElLoading.service({
        lock: true,
        text: '数据载入中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      })
    }
    /*
     *params会拼接到url上
     * */
    if (request.isParams) {
      request.params = request.data
      request.data = {}
    }
    return request
  },
  (err) => {
    Promise.reject(err)
  }
)
// 响应拦截
service.interceptors.response.use(
  (res) => {
    if (requestData.afHLoading && loadingE) {
      loadingE.close()
    }
    // 如果是下载文件直接返回
    if (requestData.isDownLoadFile) {
      return res.data
    }
    const { success, err } = res.data
    if (!success) { //失败
      if(res.data.err && (res.data.err=='token无效' || res.data.err=='token失效')){
        sessionStorage.clear()
        router.replace({path: '/',query: {}})
      }
      if(requestData.isAlertErrorMsg){//且前端指定要弹框
        ElMessage({ message: err, type: 'error', duration: 2 * 1000 })
        return Promise.reject(err)
      }else{
        return Promise.reject(err)
      }
    }
    return res.data
  },
  (err) => {
    if (loadingE) loadingE.close()
    if(err == "登录已过期，请重新登录"){
      sessionStorage.clear()
      router.replace({path: '/',query: {}})
    }else{
      ElMessage({ message: err, type: 'error', duration: 2 * 1000 })
    }
    
    return Promise.reject(err)
  }
)

export default function khReqMethod({
  url,
  data,
  method,
  progress,
  isParams,
  bfLoading,
  afHLoading,
  isUploadFile,
  isDownLoadFile,
  baseURL,
  timeout,
  isAlertErrorMsg
}) {
  return service({
    url: url,
    method: method ?? 'post',
    data: data ?? {},
    progress: progress,
    isParams: isParams ?? false,
    bfLoading: bfLoading ?? true,
    afHLoading: afHLoading ?? true,
    isUploadFile: isUploadFile ?? false,
    isDownLoadFile: isDownLoadFile ?? false,
    isAlertErrorMsg: isAlertErrorMsg ?? true,
    baseURL: settings.globalUrl.server ?? import.meta.env.VITE_APP_BASE_URL, // 设置基本基础url
    timeout: timeout // 配置默认超时时间
  })
}
